package qie2035.gs.swicher;

import android.app.Activity;
import android.content.Intent;
import android.content.UriPermission;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import qie2035.gs.swicher.MainActivity;

public class MainActivity extends Activity implements OnClickListener {

	private static final int REQUEST_CODE_FOR_DIR = 11;
	private static final String DATA_DIR_URI_FULL = "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3AAndroid%2Fdata";
	private static final String DATA_DIR_URI = "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata";
	private static final String MIHIYO_SERVER = "com.miHoYo.Yuanshen";
	private static final String BILIBILI_SERVER = "com.miHoYo.ys.bilibili";

	private TextView serverText;
	private Button switchButton;
	private Button launchButton;

	private enum Server { NONE, MIHOYO, BILIBILI }
	private Server server = Server.NONE;


	@Override
	public void onClick(View clickedView) {
		switch (clickedView.getId()) {
			case R.id.switchButton:
				switchServer();
				break;
			case R.id.launchButton:
				launch();
				break;
		}
	}

	private void launch() {
		switch (server) {
			case MIHOYO:
				launchByPackName(MIHIYO_SERVER);
				break;
			case BILIBILI:
				launchByPackName(BILIBILI_SERVER);
				break;
			case NONE:
				Toast.makeText(this, "无法确认启动哪个服", 1).show();
				break;
		}
	}

	private void switchServer() {
		try {
			switch (server) {
				case MIHOYO:
					DocumentsContract.renameDocument(getContentResolver(), Uri.parse(DATA_DIR_URI_FULL + "%2F" + MIHIYO_SERVER), BILIBILI_SERVER);
					break;
				case BILIBILI:
					DocumentsContract.renameDocument(getContentResolver(), Uri.parse(DATA_DIR_URI_FULL + "%2F" + BILIBILI_SERVER), MIHIYO_SERVER);
					break;
			}
		} catch (Exception e) {}

		updateServer();
	}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

		serverText = findViewById(R.id.serverText);
		switchButton = findViewById(R.id.switchButton);
		launchButton = findViewById(R.id.launchButton);

		switchButton.setOnClickListener(this);
		launchButton.setOnClickListener(this);

		if (!hasDataDirPermission()) {
			getDataDirPermission();
		}
    }

	@Override
	protected void onResume() {
		super.onResume();
		updateServer();
	}

	private void updateServer() {
		boolean bilibili = false,miHoYo = false;

		try {
			DocumentsContract.getDocumentMetadata(getContentResolver(), Uri.parse(DATA_DIR_URI_FULL + "%2F" + MIHIYO_SERVER));
			miHoYo = true;
		} catch (Exception e) {}

		try {
			DocumentsContract.getDocumentMetadata(getContentResolver(), Uri.parse(DATA_DIR_URI_FULL + "%2F" + BILIBILI_SERVER));
			bilibili = true;
		} catch (Exception e) {}

		String serverName = "未知";
        server = Server.NONE;

		if (!(bilibili && miHoYo)) {
			if (bilibili) {
				serverName = "B服";
				server = Server.BILIBILI;
			} else if (miHoYo) {
				serverName = "官服";
				server = Server.MIHOYO;
			}
		}

		serverText.setText(serverName);

	}

	private boolean hasDataDirPermission() {
        for (UriPermission persistedUriPermission : this.getContentResolver().getPersistedUriPermissions()) {
            if (persistedUriPermission.isReadPermission() && persistedUriPermission.getUri().toString().equals(DATA_DIR_URI)) {
                return true;
            }
        }
        return false;
    }

	private void getDataDirPermission() {
		Uri dataDirUri = Uri.parse(DATA_DIR_URI_FULL);
		Intent openDocIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
		openDocIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
							   | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
							   | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
							   | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
		openDocIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, dataDirUri);
		startActivityForResult(openDocIntent, REQUEST_CODE_FOR_DIR);
	}

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri uri;

        if (data == null) {
            return;
        }

        if (requestCode == REQUEST_CODE_FOR_DIR && (uri = data.getData()) != null) {
            getContentResolver().takePersistableUriPermission(uri, data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION
															  | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
		}

    }
	private void launchByPackName(String packName) {
		PackageManager packageManager = getPackageManager();
		if (checkPackInfo(packName)) {
			Intent intent = packageManager.getLaunchIntentForPackage(packName);
			startActivity(intent);
		} else {
			Toast.makeText(this, "没有安装这个服？", 1).show();
		}
	}

    private boolean checkPackInfo(String packName) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = getPackageManager().getPackageInfo(packName, 0);
        } catch (Exception e) {
        }
        return packageInfo != null;
    }

} 
